package com.ruoyi.common.utils.ftp;

import ch.ethz.ssh2.*;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.StringUtils;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 历史数据Controller
 *
 * @author wangshuo
 * @date 2021-01-07
 */

public class FtpUtil {

    public static List<Object> getSubfolderName(String romoteAddr,String username,
                                                String password,String targetFolder) {

        List<Object> folderNameList = new ArrayList<Object>();
        try {
            Connection connection = new Connection(romoteAddr);// 创建一个连接实例
            connection.connect();// Now connect
            boolean isAuthenticated = connection.authenticateWithPassword(username, password);//認證
            Assert.isTrue(isAuthenticated, "用戶名或密碼錯誤！");
            Session sess = connection.openSession();// 創建一個會話
            sess.requestPTY("bash");
            sess.startShell();
            InputStream stdout = new StreamGobbler(sess.getStdout());
            InputStream stderr = new StreamGobbler(sess.getStderr());
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
            //向服务器上输入命令
            PrintWriter out = new PrintWriter(sess.getStdin());
            out.println("cd " + targetFolder);//進入日志文件存放的目录
            out.println("ls -ld */");
            out.println("exit");
            out.close();
            sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,30000);

            //本机查看远程操作的指令及状态
            System.out.println("输入指令后对应的显示信息：");
            while (true) {
                String line = stdoutReader.readLine();
                if (line == null)
                    break;
                System.out.println(line);
                //取出文件夹那条记录
                if(line.contains("drwxr-xr-x")){
                    //取出正确的文件夹名
                    StringBuffer sb =
                            new StringBuffer(line.substring(line.lastIndexOf(" "),line.lastIndexOf("/")));
                    line = sb.toString().replace(" ", "");
                    folderNameList.add(line);
                }
            }
            System.out.println("ExitCode: " + sess.getExitStatus());

            //关闭连接
            sess.close();
            connection.close();
            stderrReader.close();
            stdoutReader.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(2);
        }
        return folderNameList;
    }

    public static ArrayList<String> getLinuxFileList(String surveillancePicPath,String romoteAddr,String username,
                                                 String password) {
        //创建远程连接，默认连接端口为22，如果不使用默认，可以使用方法
        //new Connection(ip, port)创建对象
//        String ip = "10.0.8.1";
//        String usr = "root";
//        String pwd = "root";
        //int port=22;
        Connection conn = null;
        String date = "";
        //所要查询的目录
//        String path = surveillancePicPath;
        if(StringUtils.isBlank(surveillancePicPath)){
            throw  new BaseException("目标目录不能为空");
        }
        ArrayList<String> filesNameList = new ArrayList<String>();
        try {
            //连接远程服务器
            // 连接部署服务器
            conn = new Connection(romoteAddr);
            conn.connect();
            //使用用户名和密码登录
            boolean b = conn.authenticateWithPassword(username, password);
            if (!b) {
                throw new IOException("Authentication failed.");
            } else {
                SFTPv3Client sft = new SFTPv3Client(conn);
//                Vector<SFTPv3DirectoryEntry> v = sft.ls(path);
                List<SFTPv3DirectoryEntry> ls = sft.ls(surveillancePicPath);
                for (int i = 0; i < ls.size(); i++) {
                    SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry();
                    s = (SFTPv3DirectoryEntry) ls.get(i);
                    String longEntry = s.longEntry;
                    //文件名
                    String filename = s.filename;
                    if(longEntry.startsWith("-")){
                        //文件
                        if (filename.endsWith("jpg")) {
                            filesNameList.add(filename);
                        }
                    }else if(longEntry.startsWith("d")) {
                        //文件夹
                    }
                }
            }
            conn.close();
        } catch (IOException e) {
            System.err.printf("用户%s密码%s登录服务器%s失败！", username, password, romoteAddr);
            e.printStackTrace();
        }

        return filesNameList;
    }


}
